package com.ibm.member.common.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {

    private static final Logger log = LoggerFactory.getLogger(DateUtil.class);

    private static final DateFormat yMdHms = new SimpleDateFormat("yyyyMMddHHmmss");

    private static final DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");

    private static final DateFormat HHmmss = new SimpleDateFormat("HHmmss");

    private static final DateFormat MMdd = new SimpleDateFormat("MMdd");

    public static void main(String[] args) throws ParseException {
        Date d = yyyyMMdd.parse("19930310");
        System.out.println(getAge(d));
    }

    public static Date parse(String dateStr) {
        try {
            return yyyyMMdd.parse(dateStr);
        } catch (ParseException e) {
            log.error("日期格式错误" + dateStr, e);
            return null;
        }
    }

    public static String formatyMdHms(Date date) {
        if (date != null)
            return yMdHms.format(date);
        return null;
    }
    
    public static String format(Date date) {
        if (date != null)
            return yyyyMMdd.format(date);
        return null;
    }

    public static String formatHHmmss(Date date) {
        if (date != null)
            return HHmmss.format(date);
        return null;
    }

    public static String formatMMdd(Date date) {
        if (date != null)
            return MMdd.format(date);
        return null;
    }
    
    /** 计算年龄 */
    public static Integer getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            log.warn("计算年龄：出生时间大于当前时间!" + birthDay.toString());
            return null;
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }

    public static Date newDate() {
        return new Date();
    }
}